import Factory.AgriculturalMachine;
import Observer.EnvironmentData;
import Strategy.*;

import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class PathPlanningManager extends SystemManager {
    private PathPlanner pathPlanner;
    private EnvironmentData data;
    private MachineManager machineManager; // 新增：引用MachineManager

    public PathPlanningManager(Scanner scanner, PathPlanner pathPlanner,
                               MachineManager machineManager, EnvironmentData data) {
        super(scanner);
        this.pathPlanner = pathPlanner;
        this.machineManager = machineManager; // 初始化引用
        this.data = data;
    }


    // 获取当前所有农机的方法
    private List<AgriculturalMachine> getRegisteredMachines() {
        if (machineManager == null) {
            return Collections.emptyList();
        }
        return machineManager.getMachines();
    }

    @Override
    public void manage() {
        while (true) {
            System.out.println("\n=== 智能路径规划 ===");
            System.out.println("1. 标准路径规划");
            System.out.println("2. 避障路径规划");
            System.out.println("3. 返回主菜单");

            int choice = getUserChoice(1, 3, "请输入选择(1-3): ");

            if (choice == 3) {
                return;
            }

            switch (choice) {
                case 1:
                    // 单农机标准路径
                    List<AgriculturalMachine> machines = getRegisteredMachines();
                    if (machines.isEmpty()) {
                        System.out.println("错误: 没有配置农机");
                        break;
                    }

                    // 为第一台农机规划路径
                    pathPlanner.setStrategy(new StandardPathPlanning(data));
                    Path singlePath = pathPlanner.planPath(new FieldMap(), data);
                    System.out.println("单农机路径: " + singlePath);
                    break;

                case 2:
                    // 多农机协同避障路径
                    List<AgriculturalMachine> allMachines = getRegisteredMachines();
                    if (allMachines.isEmpty()) {
                        System.out.println("错误: 没有配置农机");
                        break;
                    }

                    MultiMachinePathPlanner multiPlanner = new MultiMachinePathPlanner(allMachines, data);
                    multiPlanner.addStrategy(new StandardPathPlanning(data));
                    multiPlanner.addStrategy(new ObstacleAvoidancePathPlanning(data, allMachines));

                    List<Path> multiPaths = multiPlanner.planPaths(new FieldMap(), data);
                    System.out.println("多农机协同路径:");
                    for (int i = 0; i < multiPaths.size(); i++) {
                        System.out.println("农机" + (i + 1) + ": " + multiPaths.get(i));
                    }
                    break;
            }
        }
    }
}